<template>
  <div class="flex h-full">
    <a-card class="mr-2 py-2 h-full" :body-style="{ height: '100%', padding: '0 8px', display: 'flex', flexDirection: 'column' }">
      <SearchComb class="w-72" placeholder="姓名/助记码/卡号/手机号/证件号码" :show-date="false" @search="queryTabs" />
      <div class="mt-2">
        <a-radio-group v-model:value="category" button-style="solid" class="flex radio-style" @change="onChangeTab">
          <a-radio-button :value="1">
            <span class="text-lg mr-1">{{ listDataSource?.waitingQueue?.length }}</span>
            <span class="text-xs">候诊中</span>
          </a-radio-button>
          <a-radio-button :value="2">
            <span class="text-lg mr-1">{{ listDataSource?.returnQueue?.length }}</span>
            <span class="text-xs">待回诊</span>
          </a-radio-button>
          <a-radio-button :value="3">
            <span class="text-lg mr-1">{{ listDataSource?.finishQueue?.length }}</span>
            <span class="text-xs">已完诊</span>
          </a-radio-button>
        </a-radio-group>
      </div>
      <BaseList :data-source="listData" :loading="loading" class-val="w-72">
        <template #renderItem="{ item }">
          <div class="py-2 px-3">
            <div class="flex justify-between">
              <div class="flex items-center">
                <div class="text-base font-bold text-primary truncate w-20" :title="item.brName">
                  {{ item.brName }}
                </div>
                <span class="mx-2">{{ item.brSex }}</span>
                <span>{{ item.brAge }}</span>
              </div>
              <div class="flex items-center">
                <!-- <div v-if="category === 1" class="w-8">{{ item.outOrder }}人</div> -->
                <div class="w-m-12 mr-1">{{ item.queueNo }}</div>
                <a-dropdown placement="bottomRight" :get-popup-container="(trigger) => trigger.parentNode" destroy-popup-on-hide>
                  <template #overlay>
                    <a-menu class="text-center">
                      <a-menu-item v-for="(action, i) in actionArray" :key="i">
                        <BaseButton size="small" type="link" @click="onClickVisit(item, action.type)">{{ action.title }}</BaseButton>
                      </a-menu-item>
                    </a-menu>
                  </template>
                  <div class="px-1 py-1 hover:bg-slate-200 rounded">
                    <MoreOutlined class="text-base" />
                  </div>
                </a-dropdown>
              </div>
            </div>
          </div>
        </template>
      </BaseList>
      <div class="border text-center h-8 flex items-center justify-center mt-2">{{ regionName || '-' }}</div>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <a-card class="w-full flex-1">
        <div class="mb-2">
          <a-radio-group v-model:value="queueId" button-style="solid" @change="onChangeDept">
            <a-radio-button v-for="(item, index) in deptList" :key="index" :value="item.queueId" class="m-w-56 text-center">
              <span>{{ item.ksmc }}</span
              >/
              <span>{{ item.ghlb }}</span>
              <span v-if="item.empName">/{{ item.empName }}</span>
            </a-radio-button>
          </a-radio-group>
        </div>
        <BaseTable :loading="loading" row-key="id" column-code="000578" :data-source="tableData" fill :extra-height="26" :pagination="false">
          <template #bodyCell="{ column, index, record }">
            <template v-if="column.dataIndex === 'pdStatus'">
              <a-tag v-if="record.pdStatus === 'WAITING'" color="blue">未呼叫</a-tag>
              <a-tag v-else-if="record.pdStatus === 'RING'" color="green">已呼叫</a-tag>
              <a-tag v-else-if="record.pdStatus === 'DISABLE'" color="red">已停呼</a-tag>
              <span v-else>-</span>
            </template>
            <template v-if="column.dataIndex === 'brName'">
              <div v-if="record.outOrder <= configIdx" class="flex justify-between">
                <span>{{ record.brName }}</span>
                <a-tag color="geekblue">诊间屏</a-tag>
              </div>
              <div v-else>
                <span>{{ record.brName }}</span>
              </div>
            </template>
            <template v-if="column.dataIndex === 'empName'">
              <EditCell title="empName">
                <SelectDoctor
                  v-model:value="record.empName"
                  select-mode="combobox"
                  trigger="focus"
                  allow-clear
                  :disabled="record.pdStatus === 'DISABLE'"
                  :search-params="{ ghlbid: record.ghlbId, ksdm: record.ksdm, empId: record.empId }"
                  :auto-mark="false"
                  @change="onChangeDoctor($event, record)"
                />
              </EditCell>
            </template>
            <template v-if="column.dataIndex === 'action'">
              <div class="flex justify-around">
                <a-button
                  shape="circle"
                  :disabled="record.outOrder <= configIdx || record.pdStatus === 'DISABLE'"
                  :icon="h(ArrowUpOutlined)"
                  @click="onChangeSort(record, index, 'up')"
                />
                <a-button
                  shape="circle"
                  :disabled="record.outOrder <= configIdx || record.pdStatus === 'DISABLE'"
                  :icon="h(ArrowDownOutlined)"
                  @click="onChangeSort(record, index, 'down')"
                />
                <a-button
                  shape="circle"
                  :disabled="record.outOrder <= configIdx || record.pdStatus === 'DISABLE'"
                  :icon="h(VerticalAlignTopOutlined)"
                  @click="onChangeSort(record, index, 'top')"
                />
                <a-button
                  shape="circle"
                  :disabled="index === tableData.length - 1 || record.outOrder <= configIdx || record.pdStatus === 'DISABLE'"
                  :icon="h(VerticalAlignBottomOutlined)"
                  @click="onChangeSort(record, index, 'bot')"
                />
                <BaseButton
                  :confirm-text="`确定将【${record.brName}】患者移除出队列吗？`"
                  shape="circle"
                  :disabled="record.outOrder <= configIdx || record.pdStatus === 'DISABLE'"
                  :icon="h(CloseOutlined)"
                  @click="onChangeStatus(record.id)"
                />
              </div>
            </template>
          </template>
          <template #title>
            <div class="flex justify-between">
              <BaseTitle :title="formatTitle()" />
              <SyncOutlined class="cursor-pointer mr-2" @click="getDeptPatientList()" />
            </div>
          </template>
        </BaseTable>
      </a-card>
    </div>
    <SignInModal v-model:open="signOpen" :row-data="selectList" @success="queryTabs" />
    <Queue v-model:open="queueOpen" />
  </div>
</template>

<script setup>
import { ref, h, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  MoreOutlined,
  SyncOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  CloseOutlined,
  VerticalAlignTopOutlined,
  VerticalAlignBottomOutlined
} from '@ant-design/icons-vue'
import SearchComb from '@/components/SearchComb'
import { post } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
import BaseList from '@/components/BaseList'
import SelectDoctor from '../../components/SelectDoctor.vue'
import SignInModal from './SignInModal.vue'
import Queue from './Queue.vue'

const loading = ref(false)
const tableData = ref([])
const listDataSource = ref([])
const listData = ref([])
const selectList = ref([])
const deptList = ref([])
const queueId = ref('')
const activeDept = ref({})
const formState = ref({})
const category = ref(1)
const listInfo = ref({})
const actionArray = ref([])
const signOpen = ref(false)
const queueOpen = ref(false)
const regionId = ref('')
const regionName = ref('')
//执行
const onChangeSort = async (record, index, type) => {
  let offset = 0
  if (type === 'up') {
    offset = -1
  } else if (type === 'down') {
    offset = 1
  } else if (type === 'top') {
    const leftList = tableData.value.slice(0, index)
    const idx = leftList.filter((item) => item.outOrder > configIdx.value).length
    // const idx = configIdx.value - index
    offset = -idx
  } else {
    offset = tableData.value.length - index
  }
  const res = await post('/outp/nurseQueue/doSetOrderNum', {
    brId: record.brId,
    offset: offset,
    queueId: record.queueId,
    queueNo: record.queueNo,
    jzbh: record.keyCode
  })
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success(res.msg || '操作成功')
  queryTabs()
}

//左侧数据
const queryTabs = async (params) => {
  formState.value = { ...params, enter: false }
  loading.value = true
  listDataSource.value = []
  const { code, data, msg } = await post('/outp/nurseQueue/getQueueInfo', {
    keyword: formState.value.searchKey ? formState.value.searchKey : params?.searchKey,
    regionId: regionId.value ? regionId.value : window.openExe?.getConfigData('OUTP_DEFAULT_QUEUE_AREA_CODE')
  })
  loading.value = false
  if (code !== 0) return message.error(msg || '请求失败')
  listDataSource.value = data || []
  onChangeTab(params)
}
const onChangeTab = (params = {}) => {
  if (category.value === 1) {
    listData.value = listDataSource.value?.waitingQueue
    actionArray.value = [
      {
        title: '立即就诊',
        type: 1
      },
      {
        title: '前移3位',
        type: 3
      },
      {
        title: '前移5位',
        type: 5
      }
    ]
  } else if (category.value === 2) {
    listData.value = listDataSource.value?.returnQueue
    actionArray.value = [
      {
        title: '签到',
        type: 4
      }
    ]
  } else {
    listData.value = listDataSource.value?.finishQueue
    actionArray.value = [
      {
        title: '签到',
        type: 4
      }
    ]
  }
  if (listDataSource.value?.returnQueue.length === 1 && params?.enter) {
    selectList.value = listDataSource.value?.returnQueue[0]
    signOpen.value = true
  }
  if (listDataSource.value?.finishQueue.length === 1 && params?.enter) {
    selectList.value = listDataSource.value?.finishQueue[0]
    signOpen.value = true
  }
  if (listData.value.length > 0) {
    listInfo.value = listData.value[0]
  }
  getDeptList()
}
const getDeptList = async () => {
  const { code, data, msg } = await post('/outp/nurseQueue/getDeptList', {
    regionId: regionId.value ? regionId.value : window.openExe?.getConfigData('OUTP_DEFAULT_QUEUE_AREA_CODE')
  })
  if (code !== 0) return message.error(msg || '请求失败')
  deptList.value = data || []
  if (deptList.value.length > 0) {
    const haveData = deptList.value.filter((item) => item.queueId === queueId.value)
    if (queueId.value && haveData && haveData.length > 0) {
      activeDept.value = haveData[0]
    } else {
      activeDept.value = deptList.value[0]
      queueId.value = deptList.value[0].queueId
    }
    getPreConfig()
    getDeptPatientList(false)
  }
}
const getDeptPatientList = async (flag = true) => {
  loading.value = true
  const { code, data, msg } = await post('/outp/nurseQueue/getDeptQueueList', { queueId: queueId.value, regionId: regionId.value })
  loading.value = false
  if (code !== 0) return message.error(msg || '请求失败')
  tableData.value = data
  if (flag) queryTabs()
}

const onChangeDoctor = async (event, record) => {
  const { code, msg } = await post('/outp/nurseQueue/modifyDoctor', { empId: event?.value, id: record.id, roomId: event?.roomId })
  if (code !== 0) return message.error(msg || '请求失败')
  getDeptPatientList()
}
const onClickVisit = async (item, type) => {
  if (type === 1) {
    const { code, msg } = await post('/outp/nurseQueue/doSetTop', {
      brId: item.brId,
      offset: -1,
      queueId: item.queueId,
      queueNo: item.queueNo,
      jzbh: item.keyCode
    })
    if (code !== 0) return message.error(msg || '请求失败')
    queryTabs()
  } else if (type === 3 || type === 5) {
    const { code, msg } = await post('/outp/nurseQueue/doSetOrderNum', {
      brId: item.brId,
      offset: -type,
      queueId: item.queueId,
      queueNo: item.queueNo,
      jzbh: item.keyCode
    })
    if (code !== 0) return message.error(msg || '请求失败')
    queryTabs(formState.value)
  } else if (type === 4) {
    signOpen.value = true
    selectList.value = item
  }
}
const configIdx = ref(0)
const getPreConfig = async () => {
  const { code, data, msg } = await post('/outp/dictQueue/getPreDistributeNumConfig', { regionId: activeDept.value.regionId })
  if (code !== 0) return message.error(msg || '请求失败')
  configIdx.value = data
}
const onChangeStatus = async (id) => {
  const { code, msg } = await post('/outp/nurseQueue/doDeleteQueue', { id })
  if (code !== 0) return message.error(msg || '请求失败')
  message.success(msg || '操作成功')
  getDeptPatientList()
}
const onChangeDept = (e) => {
  queueId.value = e.target.value

  activeDept.value = deptList.value.filter((item) => {
    return item.queueId === queueId.value
  })[0]
  getPreConfig()
  getDeptPatientList()
}
const getTriageName = async () => {
  const res = await post('/outp/dictRegion/getRegionList', { regionId: regionId.value })
  if (res.code !== 0) message.error(res.msg)
  if (res.data && res.data.length > 0) regionName.value = res.data[0].regionName
}

const formatTitle = () => {
  if (activeDept.value.queueId) {
    if (activeDept.value.empName) {
      return `${activeDept.value.ksmc}/${activeDept.value.ghlb}/${activeDept.value.empName}(${tableData.value.length})`
    } else {
      return `${activeDept.value.ksmc}/${activeDept.value.ghlb}(${tableData.value.length})`
    }
  } else {
    return ''
  }
}
onMounted(() => {
  regionId.value = window.openExe?.getConfigData('OUTP_DEFAULT_QUEUE_AREA_CODE')
  if (regionId.value) getTriageName()
})
</script>

<style lang="less" scoped>
.radio-style {
  :deep(.ant-radio-button-wrapper) {
    width: 66.4%;
    padding: 0;
    text-align: center;
  }
}
</style>
